Your First AI application¶
Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.
In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.
The project is broken down into multiple steps:
- Load the image dataset and create a pipeline.
- Build and Train an image classifier on this dataset.
- Use your trained model to perform inference on flower images.
We'll lead you through each part which you'll implement in Python.
When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.
from google.colab import drive
drive.mount('/content/drive')
Mounted at /content/drive
Import Resources¶
# Install libraries
%pip --no-cache-dir install tensorflow-datasets --user
%pip --no-cache-dir install tfds-nightly --user
%pip --no-cache-dir install --upgrade tensorflow --user
%pip --no-cache-dir install keras --user
# Import necessary libraries
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub
import warnings
import matplotlib.pyplot as plt
import numpy as np
import json
from tensorflow import keras
from keras.layers import Dense
from keras.models import Sequential, load_model
# Import other necessary libraries
import os
import numpy as np
import logging
# Set up logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
warnings.filterwarnings('ignore')
# Some other recommended settings:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
tfds.disable_progress_bar()
Requirement already satisfied: tensorflow-datasets in /usr/local/lib/python3.10/dist-packages (4.9.4)
Requirement already satisfied: absl-py in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (1.4.0)
Requirement already satisfied: click in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (8.1.7)
Requirement already satisfied: dm-tree in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (0.1.8)
Requirement already satisfied: etils[enp,epath,etree]>=0.9.0 in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (1.7.0)
Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (1.25.2)
Requirement already satisfied: promise in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (2.3)
Requirement already satisfied: protobuf>=3.20 in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (3.20.3)
Requirement already satisfied: psutil in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (5.9.5)
Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (2.31.0)
Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (1.15.0)
Requirement already satisfied: termcolor in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (2.4.0)
Requirement already satisfied: toml in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (0.10.2)
Requirement already satisfied: tqdm in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (4.66.4)
Requirement already satisfied: wrapt in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (1.14.1)
Requirement already satisfied: array-record>=0.5.0 in /usr/local/lib/python3.10/dist-packages (from tensorflow-datasets) (0.5.1)
Requirement already satisfied: fsspec in /usr/local/lib/python3.10/dist-packages (from etils[enp,epath,etree]>=0.9.0->tensorflow-datasets) (2023.6.0)
Requirement already satisfied: importlib_resources in /usr/local/lib/python3.10/dist-packages (from etils[enp,epath,etree]>=0.9.0->tensorflow-datasets) (6.4.0)
Requirement already satisfied: typing_extensions in /usr/local/lib/python3.10/dist-packages (from etils[enp,epath,etree]>=0.9.0->tensorflow-datasets) (4.11.0)
Requirement already satisfied: zipp in /usr/local/lib/python3.10/dist-packages (from etils[enp,epath,etree]>=0.9.0->tensorflow-datasets) (3.18.1)
Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->tensorflow-datasets) (3.3.2)
Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->tensorflow-datasets) (3.7)
Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->tensorflow-datasets) (2.0.7)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->tensorflow-datasets) (2024.2.2)
Requirement already satisfied: six in /usr/local/lib/python3.10/dist-packages (from promise->tensorflow-datasets) (1.16.0)
Collecting tfds-nightly
Downloading tfds_nightly-4.9.4.dev202405090044-py3-none-any.whl (5.1 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 5.1/5.1 MB 19.7 MB/s eta 0:00:00
Requirement already satisfied: absl-py in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (1.4.0)
Requirement already satisfied: click in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (8.1.7)
Requirement already satisfied: dm-tree in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (0.1.8)
Requirement already satisfied: etils[enp,epath,epy,etree]>=1.6.0 in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (1.7.0)
Collecting immutabledict (from tfds-nightly)
Downloading immutabledict-4.2.0-py3-none-any.whl (4.7 kB)
Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (1.25.2)
Requirement already satisfied: promise in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (2.3)
Requirement already satisfied: protobuf>=3.20 in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (3.20.3)
Requirement already satisfied: psutil in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (5.9.5)
Requirement already satisfied: pyarrow in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (14.0.2)
Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (2.31.0)
Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (1.15.0)
Requirement already satisfied: termcolor in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (2.4.0)
Requirement already satisfied: toml in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (0.10.2)
Requirement already satisfied: tqdm in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (4.66.4)
Requirement already satisfied: wrapt in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (1.14.1)
Requirement already satisfied: array-record>=0.5.0 in /usr/local/lib/python3.10/dist-packages (from tfds-nightly) (0.5.1)
Requirement already satisfied: fsspec in /usr/local/lib/python3.10/dist-packages (from etils[enp,epath,epy,etree]>=1.6.0->tfds-nightly) (2023.6.0)
Requirement already satisfied: importlib_resources in /usr/local/lib/python3.10/dist-packages (from etils[enp,epath,epy,etree]>=1.6.0->tfds-nightly) (6.4.0)
Requirement already satisfied: typing_extensions in /usr/local/lib/python3.10/dist-packages (from etils[enp,epath,epy,etree]>=1.6.0->tfds-nightly) (4.11.0)
Requirement already satisfied: zipp in /usr/local/lib/python3.10/dist-packages (from etils[enp,epath,epy,etree]>=1.6.0->tfds-nightly) (3.18.1)
Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->tfds-nightly) (3.3.2)
Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->tfds-nightly) (3.7)
Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->tfds-nightly) (2.0.7)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->tfds-nightly) (2024.2.2)
Requirement already satisfied: six in /usr/local/lib/python3.10/dist-packages (from promise->tfds-nightly) (1.16.0)
Installing collected packages: immutabledict, tfds-nightly
WARNING: The script tfds is installed in '/root/.local/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed immutabledict-4.2.0 tfds-nightly-4.9.4.dev202405090044
Requirement already satisfied: tensorflow in /usr/local/lib/python3.10/dist-packages (2.15.0)
Collecting tensorflow
Downloading tensorflow-2.16.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (589.8 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 589.8/589.8 MB 94.3 MB/s eta 0:00:00
Requirement already satisfied: absl-py>=1.0.0 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (1.4.0)
Requirement already satisfied: astunparse>=1.6.0 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (1.6.3)
Requirement already satisfied: flatbuffers>=23.5.26 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (24.3.25)
Requirement already satisfied: gast!=0.5.0,!=0.5.1,!=0.5.2,>=0.2.1 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (0.5.4)
Requirement already satisfied: google-pasta>=0.1.1 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (0.2.0)
Collecting h5py>=3.10.0 (from tensorflow)
Downloading h5py-3.11.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (5.3 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 5.3/5.3 MB 79.0 MB/s eta 0:00:00
Requirement already satisfied: libclang>=13.0.0 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (18.1.1)
Collecting ml-dtypes~=0.3.1 (from tensorflow)
Downloading ml_dtypes-0.3.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.2 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.2/2.2 MB 319.4 MB/s eta 0:00:00
Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (3.3.0)
Requirement already satisfied: packaging in /usr/local/lib/python3.10/dist-packages (from tensorflow) (24.0)
Requirement already satisfied: protobuf!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<5.0.0dev,>=3.20.3 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (3.20.3)
Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (2.31.0)
Requirement already satisfied: setuptools in /usr/local/lib/python3.10/dist-packages (from tensorflow) (67.7.2)
Requirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (1.16.0)
Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (2.4.0)
Requirement already satisfied: typing-extensions>=3.6.6 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (4.11.0)
Requirement already satisfied: wrapt>=1.11.0 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (1.14.1)
Requirement already satisfied: grpcio<2.0,>=1.24.3 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (1.63.0)
Collecting tensorboard<2.17,>=2.16 (from tensorflow)
Downloading tensorboard-2.16.2-py3-none-any.whl (5.5 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 5.5/5.5 MB 108.9 MB/s eta 0:00:00
Collecting keras>=3.0.0 (from tensorflow)
Downloading keras-3.3.3-py3-none-any.whl (1.1 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.1/1.1 MB 385.9 MB/s eta 0:00:00
Requirement already satisfied: tensorflow-io-gcs-filesystem>=0.23.1 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (0.37.0)
Requirement already satisfied: numpy<2.0.0,>=1.23.5 in /usr/local/lib/python3.10/dist-packages (from tensorflow) (1.25.2)
Requirement already satisfied: wheel<1.0,>=0.23.0 in /usr/local/lib/python3.10/dist-packages (from astunparse>=1.6.0->tensorflow) (0.43.0)
Requirement already satisfied: rich in /usr/local/lib/python3.10/dist-packages (from keras>=3.0.0->tensorflow) (13.7.1)
Collecting namex (from keras>=3.0.0->tensorflow)
Downloading namex-0.0.8-py3-none-any.whl (5.8 kB)
Collecting optree (from keras>=3.0.0->tensorflow)
Downloading optree-0.11.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (311 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 311.2/311.2 kB 325.3 MB/s eta 0:00:00
Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2.21.0->tensorflow) (3.3.2)
Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2.21.0->tensorflow) (3.7)
Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2.21.0->tensorflow) (2.0.7)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2.21.0->tensorflow) (2024.2.2)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.10/dist-packages (from tensorboard<2.17,>=2.16->tensorflow) (3.6)
Requirement already satisfied: tensorboard-data-server<0.8.0,>=0.7.0 in /usr/local/lib/python3.10/dist-packages (from tensorboard<2.17,>=2.16->tensorflow) (0.7.2)
Requirement already satisfied: werkzeug>=1.0.1 in /usr/local/lib/python3.10/dist-packages (from tensorboard<2.17,>=2.16->tensorflow) (3.0.2)
Requirement already satisfied: MarkupSafe>=2.1.1 in /usr/local/lib/python3.10/dist-packages (from werkzeug>=1.0.1->tensorboard<2.17,>=2.16->tensorflow) (2.1.5)
Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.10/dist-packages (from rich->keras>=3.0.0->tensorflow) (3.0.0)
Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.10/dist-packages (from rich->keras>=3.0.0->tensorflow) (2.16.1)
Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.10/dist-packages (from markdown-it-py>=2.2.0->rich->keras>=3.0.0->tensorflow) (0.1.2)
Installing collected packages: namex, optree, ml-dtypes, h5py, tensorboard, keras, tensorflow
WARNING: The script tensorboard is installed in '/root/.local/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
WARNING: The scripts import_pb_to_tensorboard, saved_model_cli, tensorboard, tf_upgrade_v2, tflite_convert, toco and toco_from_protos are installed in '/root/.local/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
tf-keras 2.15.1 requires tensorflow<2.16,>=2.15, but you have tensorflow 2.16.1 which is incompatible.
Successfully installed h5py-3.11.0 keras-3.3.3 ml-dtypes-0.3.2 namex-0.0.8 optree-0.11.0 tensorboard-2.16.2 tensorflow-2.16.1
Requirement already satisfied: keras in /root/.local/lib/python3.10/site-packages (3.3.3)
Requirement already satisfied: absl-py in /usr/local/lib/python3.10/dist-packages (from keras) (1.4.0)
Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (from keras) (1.25.2)
Requirement already satisfied: rich in /usr/local/lib/python3.10/dist-packages (from keras) (13.7.1)
Requirement already satisfied: namex in /root/.local/lib/python3.10/site-packages (from keras) (0.0.8)
Requirement already satisfied: h5py in /root/.local/lib/python3.10/site-packages (from keras) (3.11.0)
Requirement already satisfied: optree in /root/.local/lib/python3.10/site-packages (from keras) (0.11.0)
Requirement already satisfied: ml-dtypes in /root/.local/lib/python3.10/site-packages (from keras) (0.3.2)
Requirement already satisfied: typing-extensions>=4.0.0 in /usr/local/lib/python3.10/dist-packages (from optree->keras) (4.11.0)
Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.10/dist-packages (from rich->keras) (3.0.0)
Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.10/dist-packages (from rich->keras) (2.16.1)
Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.10/dist-packages (from markdown-it-py>=2.2.0->rich->keras) (0.1.2)
Load the Dataset¶
Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.
The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.
# TODO: Load the dataset with TensorFlow Datasets.
# TODO: Create a training set, a validation set and a test set.
# Load the dataset with TensorFlow Datasets.
dataset, info = tfds.load('oxford_flowers102', as_supervised=True, with_info=True)
# Create a training set, a validation set and a test set.
train_size = info.splits['train'].num_examples
test_size = info.splits['test'].num_examples
validation_size = info.splits['validation'].num_examples
train_data = dataset['train']
test_data = dataset['test']
validation_data = dataset['validation']
Downloading and preparing dataset 328.90 MiB (download: 328.90 MiB, generated: 331.34 MiB, total: 660.25 MiB) to /root/tensorflow_datasets/oxford_flowers102/2.1.1... Dataset oxford_flowers102 downloaded and prepared to /root/tensorflow_datasets/oxford_flowers102/2.1.1. Subsequent calls will reuse this data.
Explore the Dataset¶
# TODO: Get the number of examples in each set from the dataset info.
# TODO: Get the number of classes in the dataset from the dataset info.
# Get the number of examples in each set from the dataset info.
num_train_examples = info.splits['train'].num_examples
num_test_examples = info.splits['test'].num_examples
num_validation_examples = info.splits['validation'].num_examples
# Get the number of classes in the dataset from the dataset info.
num_classes = info.features['label'].num_classes
# Print the number of examples and classes.
print(f"Number of training examples: {num_train_examples}")
print(f"Number of test examples: {num_test_examples}")
print(f"Number of validation examples: {num_validation_examples}")
print(f"Number of classes: {num_classes}")
Number of training examples: 1020 Number of test examples: 6149 Number of validation examples: 1020 Number of classes: 102
# TODO: Print the shape and corresponding label of 3 images in the training set.
# Print the shape and corresponding label of 3 images in the training set.
for i, (image, label) in enumerate(train_data.take(3)):
print(f"Image shape: {image.shape}, Label: {label}")
Image shape: (500, 667, 3), Label: 72 Image shape: (500, 666, 3), Label: 84 Image shape: (670, 500, 3), Label: 70
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding image label.
import matplotlib.pyplot as plt
# Get the first image and label from the training set.
for image, label in train_data.take(1):
image = image.numpy().squeeze()
label = label.numpy()
# Print the shape of the image and the corresponding label.
print(f"Image shape: {image.shape}, Label: {label}")
# Plot the image.
plt.imshow(image)
plt.title(label)
plt.colorbar()
plt.show()
Image shape: (500, 667, 3), Label: 72
Label Mapping¶
You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.
with open('label_map.json', 'r') as f:
class_names = json.load(f)
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding class name.
import matplotlib.pyplot as plt
# Get the first image and label from the training set.
for image, label in train_data.take(1):
image = image.numpy().squeeze()
label = label.numpy()
# Get the corresponding class name from the label map.
class_name = class_names[str(label)]
# Print the shape of the image and the corresponding class name.
print(f"Image shape: {image.shape}, Class name: {class_name}")
# Plot the image.
plt.imshow(image)
plt.title(class_name)
plt.colorbar()
plt.show()
Image shape: (500, 667, 3), Class name: water lily
Create Pipeline¶
# TODO: Create a pipeline for each set.
image_size = 224
print('GPU Available:', tf.test.is_gpu_available())
def format_image(image, label):
image = tf.cast(image, tf.float32)
image = tf.image.resize(image, (image_size, image_size))
image /= 255
return image, label
# Create a pipeline for each set.
train_data = train_data.shuffle(num_train_examples // 4).map(format_image).batch(64).prefetch(1)
test_data = test_data.map(format_image).batch(64).prefetch(1)
validation_data = validation_data.map(format_image).batch(64).prefetch(1)
GPU Available: True
Build and Train the Classifier¶
Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.
We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!
Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:
- Load the MobileNet pre-trained network from TensorFlow Hub.
- Define a new, untrained feed-forward network as a classifier.
- Train the classifier.
- Plot the loss and accuracy values achieved during training for the training and validation set.
- Save your trained model as a Keras model.
We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!
When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.
Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.
# TODO: Build and train your network. (using gpu)
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
# Load the MobileNet pre-trained network from TensorFlow Hub.
feature_extractor = hub.KerasLayer("https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4",
input_shape=(224, 224, 3), trainable=False)
# Define a new, untrained feed-forward network as a classifier.
classifier = Sequential([
Dense(256, activation='relu'),
Dense(102, activation='softmax')
])
# Freeze the MobileNet feature extractor layers.
feature_extractor.trainable = False
# Combine the feature extractor and classifier into a single model.
model = Sequential([
feature_extractor,
classifier
])
# Compile the model.
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train the model.
with tf.device('/GPU:0'):
history = model.fit(train_data, epochs=100, validation_data=validation_data)
# Plot the loss and accuracy values achieved during training for the training and validation set.
plt.plot(history.history['loss'], label='train_loss')
plt.plot(history.history['val_loss'], label='val_loss')
plt.legend()
plt.show()
plt.plot(history.history['accuracy'], label='train_accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.legend()
plt.show()
Epoch 1/100 16/16 [==============================] - 14s 381ms/step - loss: 4.3966 - accuracy: 0.0696 - val_loss: 3.6390 - val_accuracy: 0.2784 Epoch 2/100 16/16 [==============================] - 5s 282ms/step - loss: 2.6963 - accuracy: 0.5186 - val_loss: 2.3623 - val_accuracy: 0.5363 Epoch 3/100 16/16 [==============================] - 6s 340ms/step - loss: 1.3495 - accuracy: 0.8176 - val_loss: 1.6373 - val_accuracy: 0.6627 Epoch 4/100 16/16 [==============================] - 5s 279ms/step - loss: 0.6999 - accuracy: 0.9137 - val_loss: 1.2708 - val_accuracy: 0.7216 Epoch 5/100 16/16 [==============================] - 6s 335ms/step - loss: 0.3931 - accuracy: 0.9618 - val_loss: 1.1000 - val_accuracy: 0.7490 Epoch 6/100 16/16 [==============================] - 4s 226ms/step - loss: 0.2299 - accuracy: 0.9882 - val_loss: 0.9969 - val_accuracy: 0.7794 Epoch 7/100 16/16 [==============================] - 5s 280ms/step - loss: 0.1478 - accuracy: 0.9980 - val_loss: 0.9394 - val_accuracy: 0.7725 Epoch 8/100 16/16 [==============================] - 6s 340ms/step - loss: 0.1044 - accuracy: 0.9990 - val_loss: 0.8998 - val_accuracy: 0.7902 Epoch 9/100 16/16 [==============================] - 7s 450ms/step - loss: 0.0754 - accuracy: 1.0000 - val_loss: 0.8657 - val_accuracy: 0.7882 Epoch 10/100 16/16 [==============================] - 6s 317ms/step - loss: 0.0592 - accuracy: 1.0000 - val_loss: 0.8519 - val_accuracy: 0.7961 Epoch 11/100 16/16 [==============================] - 5s 259ms/step - loss: 0.0476 - accuracy: 1.0000 - val_loss: 0.8372 - val_accuracy: 0.7941 Epoch 12/100 16/16 [==============================] - 4s 232ms/step - loss: 0.0402 - accuracy: 1.0000 - val_loss: 0.8243 - val_accuracy: 0.7961 Epoch 13/100 16/16 [==============================] - 5s 269ms/step - loss: 0.0342 - accuracy: 1.0000 - val_loss: 0.8171 - val_accuracy: 0.7980 Epoch 14/100 16/16 [==============================] - 5s 273ms/step - loss: 0.0294 - accuracy: 1.0000 - val_loss: 0.8057 - val_accuracy: 0.8010 Epoch 15/100 16/16 [==============================] - 4s 227ms/step - loss: 0.0260 - accuracy: 1.0000 - val_loss: 0.8008 - val_accuracy: 0.8020 Epoch 16/100 16/16 [==============================] - 5s 280ms/step - loss: 0.0229 - accuracy: 1.0000 - val_loss: 0.7944 - val_accuracy: 0.8039 Epoch 17/100 16/16 [==============================] - 5s 298ms/step - loss: 0.0206 - accuracy: 1.0000 - val_loss: 0.7912 - val_accuracy: 0.8039 Epoch 18/100 16/16 [==============================] - 5s 280ms/step - loss: 0.0186 - accuracy: 1.0000 - val_loss: 0.7832 - val_accuracy: 0.8039 Epoch 19/100 16/16 [==============================] - 5s 280ms/step - loss: 0.0167 - accuracy: 1.0000 - val_loss: 0.7800 - val_accuracy: 0.8059 Epoch 20/100 16/16 [==============================] - 6s 315ms/step - loss: 0.0153 - accuracy: 1.0000 - val_loss: 0.7777 - val_accuracy: 0.8020 Epoch 21/100 16/16 [==============================] - 5s 319ms/step - loss: 0.0140 - accuracy: 1.0000 - val_loss: 0.7729 - val_accuracy: 0.8049 Epoch 22/100 16/16 [==============================] - 5s 248ms/step - loss: 0.0129 - accuracy: 1.0000 - val_loss: 0.7694 - val_accuracy: 0.8049 Epoch 23/100 16/16 [==============================] - 5s 281ms/step - loss: 0.0119 - accuracy: 1.0000 - val_loss: 0.7675 - val_accuracy: 0.8049 Epoch 24/100 16/16 [==============================] - 6s 339ms/step - loss: 0.0110 - accuracy: 1.0000 - val_loss: 0.7660 - val_accuracy: 0.8049 Epoch 25/100 16/16 [==============================] - 5s 278ms/step - loss: 0.0103 - accuracy: 1.0000 - val_loss: 0.7630 - val_accuracy: 0.8059 Epoch 26/100 16/16 [==============================] - 8s 488ms/step - loss: 0.0095 - accuracy: 1.0000 - val_loss: 0.7608 - val_accuracy: 0.8088 Epoch 27/100 16/16 [==============================] - 5s 282ms/step - loss: 0.0090 - accuracy: 1.0000 - val_loss: 0.7595 - val_accuracy: 0.8078 Epoch 28/100 16/16 [==============================] - 7s 456ms/step - loss: 0.0084 - accuracy: 1.0000 - val_loss: 0.7572 - val_accuracy: 0.8098 Epoch 29/100 16/16 [==============================] - 4s 230ms/step - loss: 0.0079 - accuracy: 1.0000 - val_loss: 0.7552 - val_accuracy: 0.8108 Epoch 30/100 16/16 [==============================] - 4s 233ms/step - loss: 0.0074 - accuracy: 1.0000 - val_loss: 0.7558 - val_accuracy: 0.8108 Epoch 31/100 16/16 [==============================] - 6s 361ms/step - loss: 0.0070 - accuracy: 1.0000 - val_loss: 0.7537 - val_accuracy: 0.8108 Epoch 32/100 16/16 [==============================] - 4s 233ms/step - loss: 0.0066 - accuracy: 1.0000 - val_loss: 0.7525 - val_accuracy: 0.8088 Epoch 33/100 16/16 [==============================] - 5s 280ms/step - loss: 0.0062 - accuracy: 1.0000 - val_loss: 0.7510 - val_accuracy: 0.8127 Epoch 34/100 16/16 [==============================] - 6s 348ms/step - loss: 0.0059 - accuracy: 1.0000 - val_loss: 0.7508 - val_accuracy: 0.8088 Epoch 35/100 16/16 [==============================] - 4s 228ms/step - loss: 0.0056 - accuracy: 1.0000 - val_loss: 0.7480 - val_accuracy: 0.8127 Epoch 36/100 16/16 [==============================] - 4s 232ms/step - loss: 0.0053 - accuracy: 1.0000 - val_loss: 0.7484 - val_accuracy: 0.8127 Epoch 37/100 16/16 [==============================] - 6s 334ms/step - loss: 0.0051 - accuracy: 1.0000 - val_loss: 0.7473 - val_accuracy: 0.8118 Epoch 38/100 16/16 [==============================] - 5s 281ms/step - loss: 0.0048 - accuracy: 1.0000 - val_loss: 0.7468 - val_accuracy: 0.8108 Epoch 39/100 16/16 [==============================] - 6s 305ms/step - loss: 0.0046 - accuracy: 1.0000 - val_loss: 0.7468 - val_accuracy: 0.8108 Epoch 40/100 16/16 [==============================] - 4s 241ms/step - loss: 0.0044 - accuracy: 1.0000 - val_loss: 0.7455 - val_accuracy: 0.8118 Epoch 41/100 16/16 [==============================] - 5s 305ms/step - loss: 0.0042 - accuracy: 1.0000 - val_loss: 0.7459 - val_accuracy: 0.8098 Epoch 42/100 16/16 [==============================] - 5s 278ms/step - loss: 0.0040 - accuracy: 1.0000 - val_loss: 0.7434 - val_accuracy: 0.8137 Epoch 43/100 16/16 [==============================] - 5s 289ms/step - loss: 0.0039 - accuracy: 1.0000 - val_loss: 0.7442 - val_accuracy: 0.8118 Epoch 44/100 16/16 [==============================] - 5s 280ms/step - loss: 0.0037 - accuracy: 1.0000 - val_loss: 0.7437 - val_accuracy: 0.8127 Epoch 45/100 16/16 [==============================] - 5s 293ms/step - loss: 0.0036 - accuracy: 1.0000 - val_loss: 0.7432 - val_accuracy: 0.8108 Epoch 46/100 16/16 [==============================] - 7s 452ms/step - loss: 0.0034 - accuracy: 1.0000 - val_loss: 0.7426 - val_accuracy: 0.8118 Epoch 47/100 16/16 [==============================] - 5s 281ms/step - loss: 0.0033 - accuracy: 1.0000 - val_loss: 0.7421 - val_accuracy: 0.8108 Epoch 48/100 16/16 [==============================] - 5s 280ms/step - loss: 0.0032 - accuracy: 1.0000 - val_loss: 0.7413 - val_accuracy: 0.8127 Epoch 49/100 16/16 [==============================] - 6s 329ms/step - loss: 0.0031 - accuracy: 1.0000 - val_loss: 0.7423 - val_accuracy: 0.8108 Epoch 50/100 16/16 [==============================] - 7s 449ms/step - loss: 0.0029 - accuracy: 1.0000 - val_loss: 0.7417 - val_accuracy: 0.8137 Epoch 51/100 16/16 [==============================] - 4s 232ms/step - loss: 0.0028 - accuracy: 1.0000 - val_loss: 0.7418 - val_accuracy: 0.8108 Epoch 52/100 16/16 [==============================] - 6s 356ms/step - loss: 0.0027 - accuracy: 1.0000 - val_loss: 0.7406 - val_accuracy: 0.8147 Epoch 53/100 16/16 [==============================] - 5s 281ms/step - loss: 0.0026 - accuracy: 1.0000 - val_loss: 0.7401 - val_accuracy: 0.8118 Epoch 54/100 16/16 [==============================] - 4s 237ms/step - loss: 0.0026 - accuracy: 1.0000 - val_loss: 0.7403 - val_accuracy: 0.8137 Epoch 55/100 16/16 [==============================] - 8s 518ms/step - loss: 0.0025 - accuracy: 1.0000 - val_loss: 0.7412 - val_accuracy: 0.8118 Epoch 56/100 16/16 [==============================] - 5s 280ms/step - loss: 0.0024 - accuracy: 1.0000 - val_loss: 0.7401 - val_accuracy: 0.8137 Epoch 57/100 16/16 [==============================] - 7s 454ms/step - loss: 0.0023 - accuracy: 1.0000 - val_loss: 0.7406 - val_accuracy: 0.8127 Epoch 58/100 16/16 [==============================] - 4s 225ms/step - loss: 0.0022 - accuracy: 1.0000 - val_loss: 0.7400 - val_accuracy: 0.8147 Epoch 59/100 16/16 [==============================] - 7s 451ms/step - loss: 0.0022 - accuracy: 1.0000 - val_loss: 0.7398 - val_accuracy: 0.8147 Epoch 60/100 16/16 [==============================] - 4s 229ms/step - loss: 0.0021 - accuracy: 1.0000 - val_loss: 0.7401 - val_accuracy: 0.8137 Epoch 61/100 16/16 [==============================] - 5s 331ms/step - loss: 0.0020 - accuracy: 1.0000 - val_loss: 0.7396 - val_accuracy: 0.8147 Epoch 62/100 16/16 [==============================] - 4s 227ms/step - loss: 0.0020 - accuracy: 1.0000 - val_loss: 0.7398 - val_accuracy: 0.8137 Epoch 63/100 16/16 [==============================] - 8s 466ms/step - loss: 0.0019 - accuracy: 1.0000 - val_loss: 0.7399 - val_accuracy: 0.8147 Epoch 64/100 16/16 [==============================] - 5s 282ms/step - loss: 0.0019 - accuracy: 1.0000 - val_loss: 0.7397 - val_accuracy: 0.8137 Epoch 65/100 16/16 [==============================] - 5s 280ms/step - loss: 0.0018 - accuracy: 1.0000 - val_loss: 0.7397 - val_accuracy: 0.8127 Epoch 66/100 16/16 [==============================] - 6s 342ms/step - loss: 0.0018 - accuracy: 1.0000 - val_loss: 0.7402 - val_accuracy: 0.8137 Epoch 67/100 16/16 [==============================] - 4s 234ms/step - loss: 0.0017 - accuracy: 1.0000 - val_loss: 0.7399 - val_accuracy: 0.8137 Epoch 68/100 16/16 [==============================] - 7s 456ms/step - loss: 0.0017 - accuracy: 1.0000 - val_loss: 0.7394 - val_accuracy: 0.8157 Epoch 69/100 16/16 [==============================] - 5s 279ms/step - loss: 0.0016 - accuracy: 1.0000 - val_loss: 0.7398 - val_accuracy: 0.8167 Epoch 70/100 16/16 [==============================] - 5s 288ms/step - loss: 0.0016 - accuracy: 1.0000 - val_loss: 0.7400 - val_accuracy: 0.8167 Epoch 71/100 16/16 [==============================] - 5s 298ms/step - loss: 0.0015 - accuracy: 1.0000 - val_loss: 0.7405 - val_accuracy: 0.8167 Epoch 72/100 16/16 [==============================] - 5s 283ms/step - loss: 0.0015 - accuracy: 1.0000 - val_loss: 0.7393 - val_accuracy: 0.8167 Epoch 73/100 16/16 [==============================] - 5s 275ms/step - loss: 0.0014 - accuracy: 1.0000 - val_loss: 0.7398 - val_accuracy: 0.8176 Epoch 74/100 16/16 [==============================] - 4s 235ms/step - loss: 0.0014 - accuracy: 1.0000 - val_loss: 0.7401 - val_accuracy: 0.8176 Epoch 75/100 16/16 [==============================] - 8s 478ms/step - loss: 0.0014 - accuracy: 1.0000 - val_loss: 0.7403 - val_accuracy: 0.8147 Epoch 76/100 16/16 [==============================] - 5s 284ms/step - loss: 0.0013 - accuracy: 1.0000 - val_loss: 0.7402 - val_accuracy: 0.8167 Epoch 77/100 16/16 [==============================] - 7s 453ms/step - loss: 0.0013 - accuracy: 1.0000 - val_loss: 0.7399 - val_accuracy: 0.8167 Epoch 78/100 16/16 [==============================] - 5s 280ms/step - loss: 0.0013 - accuracy: 1.0000 - val_loss: 0.7404 - val_accuracy: 0.8176 Epoch 79/100 16/16 [==============================] - 5s 286ms/step - loss: 0.0012 - accuracy: 1.0000 - val_loss: 0.7410 - val_accuracy: 0.8186 Epoch 80/100 16/16 [==============================] - 6s 327ms/step - loss: 0.0012 - accuracy: 1.0000 - val_loss: 0.7401 - val_accuracy: 0.8186 Epoch 81/100 16/16 [==============================] - 4s 231ms/step - loss: 0.0012 - accuracy: 1.0000 - val_loss: 0.7404 - val_accuracy: 0.8186 Epoch 82/100 16/16 [==============================] - 5s 333ms/step - loss: 0.0012 - accuracy: 1.0000 - val_loss: 0.7409 - val_accuracy: 0.8186 Epoch 83/100 16/16 [==============================] - 5s 279ms/step - loss: 0.0011 - accuracy: 1.0000 - val_loss: 0.7413 - val_accuracy: 0.8176 Epoch 84/100 16/16 [==============================] - 6s 352ms/step - loss: 0.0011 - accuracy: 1.0000 - val_loss: 0.7414 - val_accuracy: 0.8176 Epoch 85/100 16/16 [==============================] - 5s 278ms/step - loss: 0.0011 - accuracy: 1.0000 - val_loss: 0.7410 - val_accuracy: 0.8186 Epoch 86/100 16/16 [==============================] - 6s 338ms/step - loss: 0.0011 - accuracy: 1.0000 - val_loss: 0.7415 - val_accuracy: 0.8176 Epoch 87/100 16/16 [==============================] - 4s 233ms/step - loss: 0.0010 - accuracy: 1.0000 - val_loss: 0.7410 - val_accuracy: 0.8186 Epoch 88/100 16/16 [==============================] - 4s 230ms/step - loss: 0.0010 - accuracy: 1.0000 - val_loss: 0.7411 - val_accuracy: 0.8176 Epoch 89/100 16/16 [==============================] - 6s 350ms/step - loss: 9.8231e-04 - accuracy: 1.0000 - val_loss: 0.7421 - val_accuracy: 0.8186 Epoch 90/100 16/16 [==============================] - 4s 229ms/step - loss: 9.6187e-04 - accuracy: 1.0000 - val_loss: 0.7415 - val_accuracy: 0.8167 Epoch 91/100 16/16 [==============================] - 5s 280ms/step - loss: 9.4042e-04 - accuracy: 1.0000 - val_loss: 0.7424 - val_accuracy: 0.8157 Epoch 92/100 16/16 [==============================] - 6s 344ms/step - loss: 9.2081e-04 - accuracy: 1.0000 - val_loss: 0.7422 - val_accuracy: 0.8186 Epoch 93/100 16/16 [==============================] - 5s 277ms/step - loss: 9.0046e-04 - accuracy: 1.0000 - val_loss: 0.7421 - val_accuracy: 0.8186 Epoch 94/100 16/16 [==============================] - 6s 301ms/step - loss: 8.8148e-04 - accuracy: 1.0000 - val_loss: 0.7425 - val_accuracy: 0.8167 Epoch 95/100 16/16 [==============================] - 5s 279ms/step - loss: 8.6240e-04 - accuracy: 1.0000 - val_loss: 0.7424 - val_accuracy: 0.8167 Epoch 96/100 16/16 [==============================] - 6s 314ms/step - loss: 8.4610e-04 - accuracy: 1.0000 - val_loss: 0.7423 - val_accuracy: 0.8157 Epoch 97/100 16/16 [==============================] - 5s 314ms/step - loss: 8.2668e-04 - accuracy: 1.0000 - val_loss: 0.7439 - val_accuracy: 0.8167 Epoch 98/100 16/16 [==============================] - 4s 227ms/step - loss: 8.1054e-04 - accuracy: 1.0000 - val_loss: 0.7436 - val_accuracy: 0.8157 Epoch 99/100 16/16 [==============================] - 6s 329ms/step - loss: 7.9444e-04 - accuracy: 1.0000 - val_loss: 0.7441 - val_accuracy: 0.8157 Epoch 100/100 16/16 [==============================] - 5s 282ms/step - loss: 7.7785e-04 - accuracy: 1.0000 - val_loss: 0.7439 - val_accuracy: 0.8176
Testing your Network¶
It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.
# TODO: Print the loss and accuracy values achieved on the entire test set.
# Print the loss and accuracy values achieved on the entire test set.
test_loss, test_accuracy = model.evaluate(test_data)
print(f"Test loss: {test_loss:.3f}")
print(f"Test accuracy: {test_accuracy:.2%}")
97/97 [==============================] - 15s 155ms/step - loss: 0.9014 - accuracy: 0.7774 Test loss: 0.901 Test accuracy: 77.74%
Save the Model¶
Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).
# TODO: Save your trained model as a Keras model.
# Save to current workspcae
model.save('/content/flower_classifier.h5')
# Save to drive
model.save('/content/drive/MyDrive/flower_classifier.h5')
Load the Keras Model¶
Load the Keras model you saved above.
# TODO: Load the Keras model
loaded_model = tf.keras.models.load_model('/content/flower_classifier.h5',
compile=False,
custom_objects={'KerasLayer': hub.KerasLayer}
)
loaded_model.summary()
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
keras_layer (KerasLayer) (None, 1280) 2257984
sequential (Sequential) (None, 102) 354150
=================================================================
Total params: 2612134 (9.96 MB)
Trainable params: 354150 (1.35 MB)
Non-trainable params: 2257984 (8.61 MB)
_________________________________________________________________
Inference for Classification¶
Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.
Image Pre-processing¶
The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).
First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.
Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.
Finally, convert your image back to a NumPy array using the .numpy() method.
# TODO: Create the process_image function
def process_image(input_image, image_size=image_size):
# image = tf.io.read_file(image_path)
image = tf.cast(input_image.copy(), tf.float32)
# image = tf.image.decode_jpeg(image, channels=3)
image = tf.image.resize(image, (224, 224))
image = image / 255.0
image = image.numpy()
return image
To check your process_image function we have provided 4 images in the ./test_images/ folder:
- cautleya_spicata.jpg
- hard-leaved_pocket_orchid.jpg
- orange_dahlia.jpg
- wild_pansy.jpg
The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.
from PIL import Image
image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)
processed_test_image = process_image(test_image)
fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()
Once you can get images in the correct format, it's time to write the predict function for making inference with your model.
Inference¶
Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.
# prompt: # TODO: Create the predict function
# def predict(image_path, model, top_k=5):
# # Load the image
# image = Image.open(image_path)
# # Preprocess the image
# processed_image = process_image(np.asarray(image))
# # Add an extra dimension to the image to represent the batch size
# processed_image = np.expand_dims(processed_image, axis=0)
# # Make a prediction using the model
# # predictions = model.predict(processed_image)
# predictions = model.predict(image)[0]
# # Get the top K most likely classes
# # top_k_probs, top_k_classes = tf.nn.top_k(predictions, k=top_k)
# top_k_probs = np.argpartition(predictions, -top_k)[-top_k:]
# predictions = predictions[top_k_probs]
# top_k_probs += 1
# # Convert the class indices to class names
# # class_names = [class_names[str(i)] for i in top_k_classes.numpy()]
# classes = top_k_probs.astype(str)
# # Return the top K most likely class labels and their probabilities
# return predictions, classes
def predict_top_classes(image_path, model, top_k):
try:
# Open and preprocess the image
processed_image = process_image(Image.open(image_path))
# Add batch dimension
processed_image = np.expand_dims(processed_image, axis=0)
# Make prediction and extract top probabilities
class_probabilities = model.predict(processed_image)[0]
top_k_indices = np.argpartition(class_probabilities, -top_k)[-top_k:]
# Get class labels (assuming labels start from 0)
class_labels = model.classes[top_k_indices] + 1
return class_probabilities[top_k_indices], class_labels
except Exception as e:
# Handle potential errors (e.g., invalid image, prediction errors)
print(f"Error during prediction: {e}")
return None, None
Sanity Check¶
It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:
- cautleya_spicata.jpg
- hard-leaved_pocket_orchid.jpg
- orange_dahlia.jpg
- wild_pansy.jpg
In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:
You can convert from the class integer labels to actual flower names using class_names.
# TODO: Plot the input image along with the top 5 classes
# Define the flower names
flowers = ['cautleya_spicata', 'hard-leaved_pocket_orchid', 'orange_dahlia', 'wild_pansy']
# Iterate over each flower
for flower in flowers:
# Define the path to the image
image_path = f'./test_images/{flower}.jpg'
# Predict probabilities and classes
probabilities, classes = predict(image_path, loaded_model, 5)
# Load the image
image = np.asarray(Image.open(image_path))
# Create subplots to display the image and class probabilities
fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2)
ax1.imshow(image, cmap = plt.cm.binary)
ax1.axis('off')
ax2.barh(np.arange(probabilities.shape[0]), probabilities)
ax2.set_aspect(0.1)
ax2.set_yticks(np.arange(probabilities.shape[0]))
ax2.set_yticklabels([class_names[k] for k in classes], size='small');
ax2.set_title('Class Probability')
ax2.set_xlim(0, 1.1)
plt.tight_layout()
1/1 [==============================] - 0s 34ms/step 1/1 [==============================] - 0s 32ms/step 1/1 [==============================] - 0s 29ms/step 1/1 [==============================] - 0s 29ms/step